package com.arcvideo.acsconnect.widget;

import android.content.Context;
import android.media.MediaPlayer;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.arcvideo.acsconnect.app.GlobalConstant;
import com.arcvideo.acsconnect.eventbus.DialingEvent;
import com.arcvideo.rtcmessage.utils.LogUtil;
import com.arcvideo.tyingyitonginhouse.R;
import com.bumptech.glide.Glide;
import com.framework.core.widget.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * @author shenmengchao
 * @version 1.0.0
 * @date 2018/9/5
 * @description
 */

public class DialingLayout extends LinearLayout {

    private final static String TAG = DialingLayout.class.getSimpleName();

    @BindView(R.id.iv_avatar_dialing)
    CircleImageView mIvAvatarDialing;
    @BindView(R.id.tv_name_dialing)
    TextView mTvNameDialing;
    @BindView(R.id.iv_hang_up_dialing)
    ImageView mIvHangUpDialing;
    @BindView(R.id.ll_root_dialing)
    LinearLayout mLlRootDialing;
    private Context mContext;
    private MediaPlayer mMediaPlayer;
    private OnDialingListener mOnDialingListener;
    private Subscription mSubscription;

    public DialingLayout(Context context) {
        this(context, null);
    }

    public DialingLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DialingLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init();
    }

    public void setOnDialingListener(OnDialingListener listener) {
        this.mOnDialingListener = listener;
    }

    public void setUserInfo(String avatar, String name) {
        Glide.with(mContext).load(avatar).into(mIvAvatarDialing);
        mTvNameDialing.setText(name);
    }

    public void show() {
        mLlRootDialing.setVisibility(View.VISIBLE);
        if (null != mMediaPlayer && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
            mMediaPlayer.setLooping(true);
        }
        mSubscription = Observable
                .interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        if (aLong > GlobalConstant.DIALING_TIMEOUT) {
                            if (null != mOnDialingListener) {
                                mOnDialingListener.onTimeout();
                            }
                        }
                    }
                });
    }

    public void dismiss() {
        LogUtil.d(TAG, "dismiss()");
        mLlRootDialing.setVisibility(View.GONE);
        LogUtil.d(TAG, "dismiss() null == mMediaPlayer : " + (null == mMediaPlayer));
        LogUtil.d(TAG, "dismiss() mMediaPlayer.isPlaying() : " + (mMediaPlayer.isPlaying()));
        if (null != mMediaPlayer) {
            LogUtil.d(TAG, "dismiss() 停止拨号音");
//            ToastUtil.showToast("停止拨号音");
            try{
                mMediaPlayer.pause();
                mMediaPlayer.stop();
                mMediaPlayer.release();
            }catch (Exception e){
                LogUtil.e(TAG, "dismiss() 停止拨号音异常 " + e.getMessage());
            }
        }
        if (null != mSubscription) {
            mSubscription.unsubscribe();
        }
        //拨号页面消失之后，除非新建，不然不会再显示出来
        EventBus.getDefault().unregister(this);
    }

    public boolean isShown() {
        return View.VISIBLE == mLlRootDialing.getVisibility();
    }

    private void init() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_dialing, this, true);
        ButterKnife.bind(this, view);
        mMediaPlayer = MediaPlayer.create(mContext, R.raw.dialing);
        EventBus.getDefault().register(this);
    }

    /**
     * 这个是接收Event消息，主要是从LiveActivity#onDestroy()中调用过来的
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DialingEvent event) {
        dismiss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_PAGE_DOWN:     //向上翻页键
            case KeyEvent.KEYCODE_MEDIA_NEXT:
                break;
            case KeyEvent.KEYCODE_PAGE_UP:     //向下翻页键
            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
                break;
            case KeyEvent.KEYCODE_ENTER:     //确定键enter
            case KeyEvent.KEYCODE_DPAD_CENTER:
                break;
            case KeyEvent.KEYCODE_BACK:
//                dismiss();
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    public interface OnDialingListener {
        void onHangUp();

        void onTimeout();
    }
}
